package com.alix.paymoney.http;

import com.alibaba.fastjson.JSON;
import com.alix.paymoney.base.App;
import com.alix.paymoney.entity.BaseBean;
import com.alix.paymoney.utils.Loger;
import com.alix.paymoney.utils.NetworkUtil;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.Call;
import retrofit2.Callback;

/**
 * Created by ${吴世芊} on 2017/3/8下午2:14.
 * Updated by  on
 * ArcheryPlus-Android
 * 本类功能:
 * 说明:
 */

public class CallManager {

    private static CallManager instance;

    private CallManager() {

    }

    public static CallManager getInstance() {
        if (instance == null) {
            synchronized (CallManager.class) {
                if (instance == null) {
                    instance = new CallManager();
                }

            }
        }
        return instance;
    }

    public void addQueue(Call call, final OnResponseListener onresponse) {

        if (!NetworkUtil.isNetAvailable(App.getInstance())) {
            Loger.e("网络不可用");
            onresponse.onException("网络不可用,请检查网络");

            return;
        }

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, retrofit2.Response response) {
                if (onresponse!=null){
                    if (response.code() == 200) {

                        Object body = response.body();
                        BaseBean baseBean= (BaseBean) body;
                        if (baseBean.isSuccess()){
                            Loger.e("成功");
                            onresponse.Success(body);
                        }else {
                            Loger.e("失败");
                            onresponse.onFailed(baseBean.getCode(), baseBean.getMsg());
                        }

                    }else {
                        Loger.e(response.code() + " " + response.message() + " " + JSON.toJSONString(response.errorBody()));
                        onresponse.onException("系统异常，请重试");
                    }
                }else {
                    Loger.e("response响应空");
                }

            }
            
            @Override
            public void onFailure(Call call, Throwable t) {
                Loger.e(t.toString());
                if (onresponse!=null){
                    if (t instanceof ConnectException) {
                        onresponse.onException("网络不给力,请重试");
                    } else if (t instanceof SocketTimeoutException) {
                        onresponse.onException("网络不给力,请重试");
                    }else if (t instanceof UnknownHostException){
                        onresponse.onException("网络不给力,请重试");
                    } else {
                        onresponse.onException("网络异常,请重试");

                    }
                }

            }
        });
    }
}
